package com.eshop.eshop2021_v1.serviceImpl;

import com.eshop.eshop2021_v1.mapper.before.AddressMapper;
import com.eshop.eshop2021_v1.pojo.Address;
import com.eshop.eshop2021_v1.pojo.User;
import com.eshop.eshop2021_v1.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author: 若若叶
 * @date: 2021/10/9 10:12 FileName: AddressServiceImpl Description:
 */
@Service
public class AddressServiceImpl implements AddressService {

  @Autowired private AddressMapper addressMapper;

  @Override
  public String addAddress(String address, HttpSession session) {
    if (null == address || "".equals(address)) {
      throw new RuntimeException("地址信息需要填写。");
    }
    User user = (User) session.getAttribute("loginUser");
    if (null == user) {
      // 重定向：浏览器重新执行一个指定的请求
      // 服务器回传一个状态码（302）给浏览器，返回一个执行的请求给浏览器
      return "redirect:/user/toLogin";
    }
    Address address1 = new Address();
    address1.setAddressDetail(address);
    address1.setCreateUser(user.getRealName());
    address1.setUserId(user.getUid());
    address1.setIsDefault(1);
    addressMapper.addAddressInfo(address1);
    return "redirect:/address/toAddressPage";
  }

  @Override
  public List<Address> getAllAddressById(HttpSession session) {
    User user = (User) session.getAttribute("loginUser");
    return addressMapper.finAllAddressInfoById(user.getUid());
  }

  @Override
  public String setDefauilAddress(Integer aid, HttpSession session) {
    User user = (User) session.getAttribute("loginUser");
    addressMapper.setNoneDefault(user.getUid());
    addressMapper.setDefauilAddress(aid, user.getUid());
    return "redirect:/address/toAddressPage";
  }

  @Override
  public String deleteAddress(Integer aid) {
    addressMapper.deleteAddress(aid);
    return "redirect:/address/toAddressPage";
  }
}
